package com.waitingresult.number;

import java.util.*;

/**
 * @Author: WangShuai
 * @CreateTime: 2024-06-21  17:27
 * @Description:
 * @Version: 1.0
 */
public class OneNumber {
    public static void main(String[] args) {
        System.out.println(singleNumber(new int[]{4, 1, 2, 1, 2}));
        System.out.println(singleNumberV2(new int[]{4, 1, 2, 1, 2}));
    }

    /**
     * 原理: 相同异或得0,不同得1, 则: 两个相同的值 异或的结果 = 0,则 双数的结果 = 0,则单数的结果 == 只出现了一次的数
     *
     * @param nums
     * @return
     */
    public static int singleNumberV2(int[] nums) {
        int result = 0;
        for (int num : nums) {
            result ^= num;
        }
        return result;

    }

    public static int singleNumber(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int num : nums) {
            if (map.containsKey(num)) {
                Integer i = map.get(num);
                map.put(num, i + 1);
            } else {
                map.put(num, 1);
            }
        }
        List<Map.Entry<Integer, Integer>> collect = map.entrySet().stream().filter(entry -> entry.getValue() == 1).toList();
        Map.Entry<Integer, Integer> integerIntegerEntry = collect.get(0);
        return integerIntegerEntry.getKey();

    }

    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) {
            return new ArrayList<>();
        }

        HashMap<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] charArray = str.toCharArray();
            Arrays.sort(charArray);
            String sortedStr = Arrays.toString(charArray);
            if (map.containsKey(sortedStr)) {
                List<String> strings = map.get(sortedStr);
                strings.add(str);
            } else {
                ArrayList<String> strList = new ArrayList<>();
                strList.add(str);
                map.put(sortedStr, strList);
            }

        }
        return null;
    }
}
